package com.lyl.momanapp.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lyl.momanapp.R;
import com.lyl.momanapp.bean.ProductTemplates;
import com.lyl.momanapp.bean.ProductTtemp;
import com.lyl.momanapp.bean.URL;
import com.lyl.momanapp.bean.Upimg;
import com.lyl.momanapp.bean.User;
import com.lyl.momanapp.bean.alipay;
import com.lyl.momanapp.bean.buy;
import com.lyl.momanapp.util.utlis.MyUtils;
import com.lyl.momanapp.util.utlis.PayResult;
import com.lyl.momanapp.util.view.MyBaseActivity;

import org.xutils.x;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import static com.lyl.momanapp.bean.URL.ID_EDIT_ADDRESS_id;
import static com.lyl.momanapp.bean.URL.ID_alipay;
import static com.lyl.momanapp.bean.URL.URL_EDIT_ADDRESS_id;
import static com.lyl.momanapp.bean.URL.Userlogin;
import static com.lyl.momanapp.bean.URL.sejiandshopURL;
import static com.lyl.momanapp.bean.URL.shopColor;
import static com.lyl.momanapp.bean.URL.shopnum;
import static com.lyl.momanapp.bean.URL.shopsize;

/**
 * 名字 梁亚龙
 * 时间 2017/10/17.
 * QQ邮箱 503934353@qq.com
 */

public class UserOrderXiaActivity extends MyBaseActivity {
    private TextView mAddress;
    private LinearLayout mpeisong, mfapiao;
    private Dialog dialog;
    private View inflate;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case URL.ID_LIST_ADDRESS: {
                    User.listAddress listAddress = new Gson().fromJson(msg.obj.toString(), User.listAddress.class);
                    if (listAddress.getState().equals("M00000")) {
                        if (listAddress.getResult().size() != 0) {
                            Log.i("1", "handleMessage: " + 11111);
                            mYou.setVisibility(View.VISIBLE);
                            mWu.setVisibility(View.GONE);
                            User.listAddress.ResultBean resultBean = listAddress.getResult().get(0);
                            mName.setText(resultBean.getConsignee());
                            mPhone.setText(resultBean.getPhone());
                            mAddressA.setText(resultBean.getProv() + " " + resultBean.getCity() + " " + resultBean.getArea() + " " + resultBean.getAddress());

                        } else {
                            mWu.setVisibility(View.VISIBLE);
                            mYou.setVisibility(View.GONE);
                        }
                    }
                }
                break;
                case ID_EDIT_ADDRESS_id: {
                    User.address_id address_id = new Gson().fromJson(msg.obj.toString(), User.address_id.class);
                    if (address_id.getState().equals("M00000")) {
                        mWu.setVisibility(View.GONE);
                        mYou.setVisibility(View.VISIBLE);

                        User.address_id.ResultBean result = address_id.getResult();
                        mName.setText(result.getConsignee());
                        mPhone.setText(result.getPhone());
                        mAddressA.setText(result.getProv() + " " + result.getCity() + " " + result.getArea() + " " + result.getAddress());

                    }
                }
                break;
                case 111111111: {
                    Log.i("111111111111111111", "handleMessage: " + msg.obj.toString());
                    Upimg upimg = new Gson().fromJson(msg.obj.toString(), Upimg.class);
//                    HashMap<String, String> map = new HashMap<>();
//                    map.put("user_id", Userlogin.getResult().getUser_id() + "");
//                    map.put("product_temp_id", productTemplates.getProduct_temp_id() + "");
//                    map.put("product_image", upimg.getResult().getOriginal_image());
//                    new MyUtils().xUtilsPost(URL.URL_product, map, handler, 22222222);
                    HashMap<String, String> map = new HashMap<>();

                    map.put("user_id", Userlogin.getResult().getUser_id() + "");
                    map.put("product_id", "2017120410198100");
                    map.put("colour_name", shopColor);
                    map.put("size_name", shopsize);
                    map.put("quantity", shopnum);
                    map.put("platform", "Android");
                    map.put("message", message.getText().toString() + "1");
                    map.put("send_type", "1");
                    map.put("address_id", URL.address_id + "");
                    map.put("invoice_type", "0");
                    map.put("delivery_time", "0");
                    map.put("is_invoice", "0");
                    map.put("invoice_list", "0");

                    new MyUtils().xUtilsPost(URL.URL_buy, map, handler, URL.ID_buy);
                }
                break;

                case 22222222: {
                    ProductTtemp productTtemp = new Gson().fromJson(msg.obj.toString(), ProductTtemp.class);
                    //                    Log.i("111111", "handleMessage: "+msg.obj.toString());
                    HashMap<String, String> map = new HashMap<>();
                    map.put("user_id", Userlogin.getResult().getUser_id() + "");
                    map.put("product_id", productTtemp.getProduct_id());
                    map.put("colour_name", shopColor);
                    map.put("size_name", shopsize);
                    map.put("quantity", shopnum);
                    map.put("platform", "Android");
                    map.put("message", message.getText().toString() + "1");
                    map.put("send_type", 1 + "");
                    map.put("mac_id", "2017052397494952");
                    map.put("total_fee", mShopZong.getText().toString());
                    map.put("address_id", URL.address_id + "");
                    map.put("has_invoice", 0 + "");
                    map.put("coupon_id", 1 + "");
                    new MyUtils().xUtilsPost(URL.URL_buy, map, handler, URL.ID_buy);
                }
                break;
                case URL.ID_buy: {
                    Log.i("11111111111", "handleMessage: " + msg.obj.toString());
                    URL.buy = new Gson().fromJson(msg.obj.toString(), buy.class);
                    if (URL.buy.getState().equals("M00000")) {
                        Toast.makeText(UserOrderXiaActivity.this, "下单成功", Toast.LENGTH_SHORT).show();
                        show();
                    } else {
                        Toast.makeText(UserOrderXiaActivity.this, URL.buy.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                }
                break;
                case ID_alipay: {
                    final alipay alipay1 = new Gson().fromJson(msg.obj.toString(), alipay.class);
                    final String orderInfo = alipay1.getResult().getOrder_info();
                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(UserOrderXiaActivity.this);
                            Map<String, String> result = alipay.payV2(orderInfo, true);
                            Log.i("msp", result.toString());

                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = result;
                            handler.sendMessage(msg);
                        }
                    };

                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
                break;
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(UserOrderXiaActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(UserOrderXiaActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }

        }
    };
    private TextView mName, mPhone, mAddressA, mAddressxiu;
    private LinearLayout mYou, mWu;
    private Button mBut;
    private CheckBox mCKweixin;
    private CheckBox mCKzhifubao;
    private ImageView mShopImg;
    private ProductTemplates.ResultBean.DataBean productTemplates;
    private TextView mShopname;
    private TextView mShopJage;
    private TextView mShopGuige;
    private TextView mShopNum;
    private TextView mShopZong;
    private TextView mShopjiage;
    private EditText message;
    private TextView mOrdernaem;

    @Override
    public void initUI() {
        setContentView(R.layout.activity_order_xia);
        mAddress = ((TextView) findViewById(R.id.order_xia_address));
        mpeisong = ((LinearLayout) findViewById(R.id.order_Xia_peisong));
        mfapiao = ((LinearLayout) findViewById(R.id.order_Xia_fapiao));
        mName = ((TextView) findViewById(R.id.address_xia_name));
        mPhone = (TextView) findViewById(R.id.address_xia_phone);
        mAddressA = (TextView) findViewById(R.id.address_xia_address);
        mYou = ((LinearLayout) findViewById(R.id.xia_address_you));
        mWu = (LinearLayout) findViewById(R.id.xia_address_wu);
        mAddressxiu = (TextView) findViewById(R.id.address_xia);
        mBut = ((Button) findViewById(R.id.order_xia_but));
        mShopImg = ((ImageView) findViewById(R.id.xia_shop_img));
        mShopname = ((TextView) findViewById(R.id.xia_shop_name));
        mShopJage = ((TextView) findViewById(R.id.xia_shop_jage));
        mShopGuige = ((TextView) findViewById(R.id.xia_shop_guige));
        mShopNum = ((TextView) findViewById(R.id.xia_shop_num));
        mShopZong = (TextView) findViewById(R.id.xia_shop_zongjage);
        mShopjiage = ((TextView) findViewById(R.id.xia_shop_shop_jage));
        message = ((EditText) findViewById(R.id.order_xia_message));
        mOrdernaem = ((TextView) findViewById(R.id.order_xia_order_name));
    }

    @Override
    public void initData() {
        if (URL.Userlogin == null) {
            startActivity(new Intent(UserOrderXiaActivity.this, UserLoginActivity.class));
        }
        productTemplates = URL.productTemplates;
        x.image().bind(mShopImg, sejiandshopURL);
        mShopname.setText(productTemplates.getProduct_temp_name());
        mShopJage.setText(productTemplates.getPreferential_price());
        mShopNum.setText(shopnum);
        mShopGuige.setText("商品型号：" + shopsize + ", " + shopColor);
        DecimalFormat df = new DecimalFormat("######0.00");
        double jage = Double.parseDouble(productTemplates.getPreferential_price()) * Double.parseDouble(shopnum);
        mShopZong.setText(df.format(jage));
        mShopjiage.setText(df.format(jage));
    }

    @Override
    public void addListeners() {
        mAddressxiu.setOnClickListener(this);
        mAddress.setOnClickListener(this);
        mpeisong.setOnClickListener(this);
        mfapiao.setOnClickListener(this);
        mBut.setOnClickListener(this);

        findViewById(R.id.order_Xia_shop).setOnClickListener(this);
        findViewById(R.id.fanhui).setOnClickListener(this);
        findViewById(R.id.zhuye).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.order_xia_address: {
                startActivity(new Intent(UserOrderXiaActivity.this, UserAddressesGuanliActivity.class));

            }
            break;
            case R.id.order_Xia_peisong: {
                startActivity(new Intent(UserOrderXiaActivity.this, UserExpressActivity.class));
            }
            break;
            case R.id.order_Xia_fapiao: {
                startActivity(new Intent(UserOrderXiaActivity.this, UserKaiFaPiaoActivity.class));
            }
            break;
            case R.id.address_xia: {
                startActivity(new Intent(UserOrderXiaActivity.this, UserAddressesGuanliActivity.class));
            }
            break;
            case R.id.order_xia_but: {
                if (URL.address_id == 0) {
                    Toast.makeText(UserOrderXiaActivity.this, "请添加地址", Toast.LENGTH_SHORT).show();
                } else {
                    udimg1();
                }
            }
            break;
            case R.id.order_Xia_shop: {
                startActivity(new Intent(UserOrderXiaActivity.this, StoresActivity.class));
            }
            break;
            case R.id.fanhui: {
                finish();
            }
            break;
            case R.id.zhuye: {

                startActivity(new Intent(UserOrderXiaActivity.this, MainActivity.class));
                finish();
            }
            break;
            case R.id.fukuan_but: {
//                HashMap<String, String> map = new HashMap<>();
//                map.put("user_id", Userlogin.getResult().getUser_id() + "");
//                map.put("order_id", URL.buy.getOrder_id());
//                map.put("platform", "Android");
//                new MyUtils().xUtilsPost(URL_alipay, map, handler, ID_alipay);
            }
            break;
        }
    }

    public void show() {
        dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        inflate = LayoutInflater.from(this).inflate(R.layout.item_fukuan, null);
        //初始化控件
        mCKweixin = ((CheckBox) inflate.findViewById(R.id.fukuan_weixin));
        mCKzhifubao = ((CheckBox) inflate.findViewById(R.id.fukuan_zhifubao));
        inflate.findViewById(R.id.fukuan_but).setOnClickListener(this);
        mCKweixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCKzhifubao.setChecked(false);
                }
            }
        });
        mCKzhifubao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCKweixin.setChecked(false);
                }
            }
        });

        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = getWindowManager().getDefaultDisplay().getWidth();
        lp.y = 20;//设置Dialog距离底部的距离
        //       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        dialog.show();//显示对话框
    }

    private void udimg1() {
        Log.i("111111111111111111", "udimg: " + sejiandshopURL);
        new MyUtils().xUutlisImg(URL.URL_img_up, sejiandshopURL, handler, 111111111);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (URL.address_id == 0) {

        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("address_id", URL.address_id + "");
            new MyUtils().xUtilsPost(URL_EDIT_ADDRESS_id, map, handler, ID_EDIT_ADDRESS_id);
        }
        mOrdernaem.setText(URL.storesname);

    }
}
